var os = require("os"),
    fs = require("fs"),
    path = require('path'),
    stylish = require('jshint-stylish'),
    combiner = require('stream-combiner2'),

    pngquant = require('imagemin-pngquant'),
    es = require('event-stream'),
    gulp = require('gulp'),
    $ = require('gulp-load-plugins')(
        {
            DEBUG: false, // when set to true, the plugin will log info to console. Useful for bug reporting and issue debugging
            pattern: ['gulp-*', 'gulp.*', '@*/gulp{-,.}*'], // the glob(s) to search for
            overridePattern: true, // When true, overrides the built-in patterns. Otherwise, extends built-in patterns matcher list.
            // config: '../package.json', // where to find the plugins, by default searched up from process.cwd()
            scope: ['dependencies', 'devDependencies', 'peerDependencies'], // which keys in the config to look within
            replaceString: /^gulp(-|\.)/, // what to remove from the name of the module when adding it to the context
            camelize: true, // if true, transforms hyphenated plugins names to camel case
            lazy: true, // whether the plugins should be lazy loaded on demand
            rename: {}, // a mapping of plugins to rename
            // renameFn: function (name) { ... }, // a function to handle the renaming of plugins (the default works)
            postRequireTransforms: {}, // see documentation below
            maintainScope: true // toggles loading all npm scopes like non-scoped packages
        }
    ),
    handleError = function (err) {
        var colors = $.util.colors;
        console.log('\n')
        $.util.log(colors.red('Error!'))
        $.util.log('fileName: ' + colors.red(err.fileName))
        $.util.log('lineNumber: ' + colors.red(err.lineNumber))
        $.util.log('message: ' + err.message)
        $.util.log('plugin: ' + colors.yellow(err.plugin))
        console.log('\n')
    },
    min_js = true,
    buildConfig = require("./build.config.js"),//构建目录
    watching_paths = {//监控目录
        js: [
            '../assets/js/lib/*.js', //工具类
            '../assets/js/ser/*.js', //公共服务
            '../assets/js/m/*.js',   //移动端 ctljs
            "../assets/js/pc/*.js",  //pc端  ctljs
        ],
        css: [
            '../assets/css/*.css',
            '../assets/css/**/*.css'
        ],
        html: [
            '../assets/html/**/*.html'
        ],
        config: ['./build.config.js']
    },
    htmlMinOptions = {
        removeComments: true,//清除HTML注释
        collapseWhitespace: true,//压缩HTML
        collapseBooleanAttributes: true,//省略布尔属性的值 <input checked="true"/> ==> <input />
        removeEmptyAttributes: true,//删除所有空格作属性值 <input id="" /> ==> <input />
        removeScriptTypeAttributes: true,//删除<script>的type="text/javascript"
        removeStyleLinkTypeAttributes: true,//删除<style>和<link>的type="text/css"
        minifyJS: true,//压缩页面JS
        minifyCSS: true//压缩页面CSS
    },
    imgMinOptions = {
        optimizationLevel: 5, //类型：Number  默认：3  取值范围：0-7（优化等级）
        progressive: true, //类型：Boolean 默认：false 无损压缩jpg图片
        interlaced: true, //类型：Boolean 默认：false 隔行扫描gif进行渲染
        multipass: true, //类型：Boolean 默认：false 多次优化svg直到完全优化
        svgoPlugins: [{removeViewBox: false}],
        use: [$.pngquant]
    };


//检测pc CSS
gulp.task('checkPcCss', function () {
    return combiner.obj([
        gulp.src(buildConfig.pccss),
        $.csslint(),
        $.csslint.reporter(),
        $.csslint.failReporter(),
    ]).on('error', handleError);
});

//压缩pc 端 图片
gulp.task('minPcImgs', function () {
    return combiner.obj([
        gulp.src(buildConfig.pcimgs),
        // $.cache(imagemin(imgMinOptions)),
        gulp.dest(buildConfig.buildPath + "imgs/pc"),
    ]).on('error', handleError);
});


//压缩公用 图片
gulp.task('minCommonImgs', function () {
    return combiner.obj([
        gulp.src(buildConfig.commonimgs),
        // $.cache(imagemin(imgMinOptions)),
        gulp.dest(buildConfig.buildPath + "imgs"),
    ]).on('error', handleError);
});

//合并压缩pc版css
gulp.task('minPcCss', function () {
    return combiner.obj([
        gulp.src(buildConfig.pccss),
        $.concat('app.css'),
        gulp.dest(buildConfig.revPath + "css/"),
        //   $.sourcemaps.init(),
        $.autoprefixer({
            browsers: 'last 2 versions'
        }),
        $.cleanCss({compatibility: 'ie8'}),
        //   $.sourcemaps.write('./'),
        $.rename({extname: '.min.css'}),
        gulp.dest(buildConfig.revPath + "css/")
    ]).on('error', handleError);
});

//检测pc JS
gulp.task('checkPcJs', function () {
    return combiner.obj([
        gulp.src(buildConfig.pcjs),
        $.jshint({
            "undef": false,
            "unused": false
        }),
        $.jshint.reporter('default'),  //错误默认提示
        $.jshint.reporter($.stylish),   //高亮提示
        $.jshint.reporter('fail'),
    ]).on('error', handleError);
});

//合并压缩pc js
gulp.task('minPcJs', ['fuckie'], function () {
    return combiner.obj([
        gulp.src(buildConfig.pcjs),
        $.concat('app.js'),
        gulp.dest(buildConfig.revPath + "js/"),
        //   $.sourcemaps.init(),
        $.if(min_js, $.uglify()),
        //    $.sourcemaps.write('./'),
        $.rename({extname: '.min.js'}),
        gulp.dest(buildConfig.revPath + "js/")
    ]).on('error', handleError)

});

//合并压缩ie8 js
gulp.task('fuckie', function () {
    return combiner.obj([
        gulp.src(buildConfig.fuckie),
        $.concat('polyfill.js'),
        gulp.dest(buildConfig.revPath + "js/"),
        //$.if(min_js, uglify()), jquery二次压缩,ie8会出问题
        $.rename({extname: '.min.js'}),
        gulp.dest(buildConfig.revPath + "js/"),
    ]).on('error', handleError);
});


//检测 mobile CSS
gulp.task('checkMCss', function () {
    return combiner.obj([
        gulp.src(buildConfig.mcss),
        $.csslint(),
        $.csslint.reporter(),
        $.csslint.failReporter(),
    ]).on('error', handleError);
});

//压缩m端图片
gulp.task('minMImgs', function () {
    return combiner.obj([
        gulp.src(buildConfig.mimgs),
        // $.cache(imagemin(imgMinOptions)),
        gulp.dest(buildConfig.buildPath + "imgs/m/"),
    ]).on('error', handleError);
});


//合并压缩 mobile css
gulp.task('minMCss', function () {
    return combiner.obj([
        gulp.src(buildConfig.mcss),
        $.concat('appm.css'),
        gulp.dest(buildConfig.revPath + "css/"),
        $.cleanCss({compatibility: 'ie8'}),
        $.rename({extname: '.min.css'}),
        gulp.dest(buildConfig.revPath + "css/")
    ]).on('error', handleError);
});

//检测 mobile JS
gulp.task('checkMJs', function () {
    return combiner.obj([
        gulp.src(buildConfig.mjs),
        $.jshint({
            "undef": false,
            "unused": false
        }),
        $.jshint.reporter('default'),  //错误默认提示
        $.jshint.reporter($.stylish),  //高亮提示
        $.jshint.reporter('fail'),
    ]).on('error', handleError);
});

//合并压缩 mobile js
gulp.task('minMJs', function () {
    return combiner.obj([
        gulp.src(buildConfig.mjs),
        $.concat('appm.js'),
        $.gulp.dest(buildConfig.revPath + "js/"),
        $.if(min_js, uglify()),
        $.rename({extname: '.min.js'}),
        gulp.dest(buildConfig.revPath + "js/"),
    ]).on('error', handleError);
});

//CSS生成文件hash编码并生成 rev-manifest.json文件名对照映射
gulp.task('revCss', function () {
    return combiner.obj([
        gulp.src(buildConfig.revPath + "css/*.min.css"),
        $.rev(),
        gulp.dest(buildConfig.buildPath + "css/"),
        $.rev.manifest(),
        gulp.dest(buildConfig.revPath + "css/"),
    ]).on('error', handleError);
});

//js生成文件hash编码并生成 rev-manifest.json文件名对照映射
gulp.task('revJs', function () {
    return combiner.obj([
        gulp.src(buildConfig.revPath + "js/*.min.js"),
        $.rev(),
        gulp.dest(buildConfig.buildPath + "js/"),
        $.rev.manifest(),
        gulp.dest(buildConfig.revPath + "js"),
    ]).on('error', handleError);
});

//html中 css/js 文件版本
gulp.task('revPCHtml', function () {
    return combiner.obj([
        gulp.src([buildConfig.revPath + '**/*.json', buildConfig.htmlPath + "pc/*.html"]),
        $.fileInclude({
            prefix: '@@',
            basepath: '@file'
        }),
        $.revCollector(),
        $.htmlmin(htmlMinOptions),
        gulp.dest(buildConfig.revHtmlPath + "pc/"),
    ]).on('error', handleError);
});

//html中 css/js 文件版本
gulp.task('revMHtml', function () {
    return combiner.obj([
        gulp.src([buildConfig.revPath + '**/*.json', buildConfig.htmlPath + "m/*.html"]),
        $.fileInclude({
            prefix: '@@',
            basepath: '@file'
        }),
        $.revCollector(),
        $.htmlmin(htmlMinOptions),
        gulp.dest(buildConfig.revHtmlPath + "m/"),
    ]).on('error', handleError);
});

//复制 iconfont 字体
gulp.task('fonts', function () {
    return combiner.obj([
        gulp.src(buildConfig.fontPath),
        gulp.dest(buildConfig.buildPath + "fonts/"),
    ]).on('error', handleError);
});

//清理缓存
gulp.task('config', function (done) {
    var pwd = path.resolve() + "/build.config.js";
    delete require.cache[pwd];
    buildConfig = require("./build.config.js");
    done();
});

//清理全部生产文件
gulp.task("cleanAll", function () {
    return combiner.obj([
        gulp.src([buildConfig.revPath + "**/*.*", buildConfig.buildPath + "**/*.{css,js}", buildConfig.buildPath + "**/**/*.{css,js}"]),
        $.clean({force: true}),
    ]).on('error', handleError);

})

//清理开发板文件
gulp.task("cleanDev", function (done) {
    return combiner.obj([
        gulp.src(buildConfig.revPath + "**/*.*"),
        $.clean({force: true}),
    ]).on('error', handleError);
})

//监听文件变动
gulp.task('watch', function () {
    gulp.watch(watching_paths.css, ['default']);
    gulp.watch(watching_paths.js, ['default']);
});
gulp.task("default", ["watch"]);
gulp.task('tdzip',['cleanZip'], function () {
    return combiner.obj([

        gulp.src(buildConfig.buildPath+"**"),
        $.zip('tdweb.zip'),
        gulp.dest(buildConfig.buildPath)
    ]).on('error', handleError);


});
gulp.task('wtzip',['cleanZip'], function () {
    return combiner.obj([

        gulp.src(buildConfig.buildPath+"**"),
        $.zip('wtweb.zip'),
        gulp.dest(buildConfig.buildPath)
    ]).on('error', handleError);


});

gulp.task("cleanZip", function () {
    return combiner.obj([
        gulp.src(buildConfig.buildPath+"wtweb.zip"),
        $.clean({force: true}),
    ]).on('error', handleError);
})


gulp.task("replaceWt", function () {
    return combiner.obj([
        gulp.src(buildConfig.htmlPath+'pc/tpl/common/commonjs.html'),
        $.template({datafile: 'huanrun_index.js'}),
        gulp.dest(buildConfig.htmlPath+'pc/tpl/')
    ]).on('error', handleError);
})


gulp.task("replaceWtTest", function () {
    return combiner.obj([
        gulp.src(buildConfig.htmlPath+'pc/tpl/common/commonjs.html'),
        $.template({datafile: 'huanrun_index_test.js'}),
        gulp.dest(buildConfig.htmlPath+'pc/tpl/')
    ]).on('error', handleError);
})

gulp.task("replaceTd", function () {
    return combiner.obj([
        gulp.src(buildConfig.htmlPath+'pc/tpl/common/commonjs.html'),
        $.template({datafile: 'tongda_index.js'}),
        gulp.dest(buildConfig.htmlPath+'pc/tpl/')
    ]).on('error', handleError);
})
gulp.task("replaceTdTest", function () {
    return combiner.obj([
        gulp.src(buildConfig.htmlPath+'pc/tpl/common/commonjs.html'),
        $.template({datafile: 'tongda_index_test.js'}),
        gulp.dest(buildConfig.htmlPath+'pc/tpl/')
    ]).on('error', handleError);
})

//压缩公用 图片
gulp.task('minWtimg', function () {
    return combiner.obj([
        gulp.src('../assets/imgs/pc/wt/*'),
        gulp.dest(buildConfig.buildPath + "imgs/pc/"),
    ]).on('error', handleError);
});

gulp.task('minTdimg', function () {
    return combiner.obj([
        gulp.src('../assets/imgs/pc/td/*'),
        gulp.dest(buildConfig.buildPath + "imgs/pc"),
    ]).on('error', handleError);
});

gulp.task("cleanSass", function () {
    return combiner.obj([
        gulp.src(buildConfig.sassPath+"0.pc.scss"),
        $.clean({force: true}),
    ]).on('error', handleError);
})


gulp.task("conWtSass",['cleanSass'], function () {
    return combiner.obj([
        gulp.src([buildConfig.sassPath+"tpl/wtvar.scss",buildConfig.sassPath+"tpl/pure.scss",buildConfig.sassPath+"tpl/common.scss"]),
        $.concat('0.pc.scss'),
        gulp.dest(buildConfig.sassPath)
    ]).on('error', handleError);
})


gulp.task("conTdSass",['cleanSass'], function () {
    return combiner.obj([
        gulp.src([buildConfig.sassPath+"tpl/tdvar.scss",buildConfig.sassPath+"tpl/pure.scss",buildConfig.sassPath+"tpl/common.scss"]),
        $.concat('0.pc.scss'),
        gulp.dest(buildConfig.sassPath)
    ]).on('error', handleError);
})

gulp.task('wtSass',['conWtSass'], function () {
    return combiner.obj([
        gulp.src(buildConfig.sassPath+"*.scss"),
        $.sourcemaps.init(),
        $.sass().on('error', $.sass.logError),
        $.sourcemaps.write(),
        gulp.dest(buildConfig.cssPath + "/pc")
    ]).on('error', handleError);
});

gulp.task('tdSass',['conTdSass'], function () {
    return combiner.obj([
        gulp.src(buildConfig.sassPath+"*.scss"),
        $.sourcemaps.init(),
        $.sass().on('error', $.sass.logError),
        $.sourcemaps.write(),
        gulp.dest(buildConfig.cssPath + "/pc")
    ]).on('error', handleError);
});

//构建世茂
gulp.task('buildWtProd', ['cleanAll'], function (done) {
    $.sequence(
        ['config'],
        ['wtSass'],
        ['fonts'],
        ['minCommonImgs'],
        // ['minPcImgs'],
        ['minPcCss'],
        ['minPcJs'],
        // ['minMCss'],
        // ['minMJs'],
        ['revCss'],
        ['revJs'],
        ['replaceWt'],
        ['minWtimg'],
        ['revPCHtml'],
        // ['revMHtml'],
        ['wtzip'],
        done);
});


//构建通达生产
gulp.task('buildTdProd', ['cleanAll'], function (done) {
    $.sequence(
        ['config'],
        ['tdSass'],
        ['fonts'],
        ['minCommonImgs'],
        // ['minPcImgs'],
        ['minPcCss'],
        ['minPcJs'],
        // ['minMCss'],
        // ['minMJs'],
        ['revCss'],
        ['revJs'],
        ['replaceTd'],
        ['minTdimg'],
        ['revPCHtml'],
        // ['revMHtml'],
        ['tdzip'],
        done);
});

//构建世茂测试
gulp.task('buildWtTest', ['cleanAll'], function (done) {
    $.sequence(
        ['config'],
        ['wtSass'],
        ['fonts'],
        ['minCommonImgs'],
        // ['minPcImgs'],
        ['minPcCss'],
        ['minPcJs'],
        // ['minMCss'],
        // ['minMJs'],
        ['revCss'],
        ['revJs'],
        ['replaceWtTest'],
        ['minWtimg'],
        ['revPCHtml'],
        // ['revMHtml'],
        ['wtzip'],
        done);
});

//构建通达测试
gulp.task('buildTdTest', ['cleanAll'], function (done) {
    $.sequence(
        ['config'],
        ['tdSass'],
        ['fonts'],
        ['minCommonImgs'],
        // ['minPcImgs'],
        ['minPcCss'],
        ['minPcJs'],
        // ['minMCss'],
        // ['minMJs'],
        ['revCss'],
        ['revJs'],
        ['replaceTdTest'],
        ['minTdimg'],
        ['revPCHtml'],
        // ['revMHtml'],
        ['tdzip'],
        done);
});


//代理服务器
// gulp.task('connect', function () {
//     connect.server({
//         host: '127.0.0.1',
//         port: 80,
//         root: '../static/', //当前项目主目录
//         livereload: true,
//         middleware: function (connect, opt) {
//             opt.route = '/proxy';
//             var proxy = new gproxy(opt);
//             return [proxy];
//         }
//     });
// });

//自动刷新
// gulp.task('html', function () {
//     gulp.src(buildConfig.html)
//       connect.reload());
// });
// gulp.task('server', ['watch','connect']);
